package com.huawei.rbac.web.Interceptor;

import com.huawei.rbac.domain.Employee;
import com.huawei.rbac.util.RequiredRermission;
import com.huawei.rbac.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

public class SecurityInterceptor extends HandlerInterceptorAdapter {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {

        // 获取当前用户
        Employee currentEmp = UserContext.getCurrentUser();
        // 判断是否是超级管理员
        System.out.println(currentEmp);
        if(currentEmp.isAdmin()){
            // 放行
            return true;
        }
        // 请求方法是否需要权限管理
        // 当前请求方法的处理器
        HandlerMethod hm = (HandlerMethod) handler;
        // 获取当前请求的方法
        Method method = hm.getMethod();
        //判断当前方法上是否有贴RequiredPermission注解
        if(!method.isAnnotationPresent(RequiredRermission.class)){
            return true;
        }
        
        //如果当前用户有访问当前方法的权限,放行

        //获取当前请求的方法需要的权限表达式
        RequiredRermission ann = method.getAnnotation(RequiredRermission.class);
        String expression = ann.value()[1];
        //获取当前拥有的所有的权限表达式
        final List<String> expressions = UserContext.getPermissionExps();
        if(expressions.contains(expression)){
            return true;
        }
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        // 拦截
        return false;
    }

}
